#include "mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>

#define FILE_MODE 0666

// "w", "a", "r"
_FILE * _fopen(const char *filename, const char *flag)           
{
    assert(filename);
    assert(flag);

    int f = 0;
    int fd = -1;
    if (strcmp(flag, "w") == 0) {
        f = (O_WRONLY | O_CREAT | O_TRUNC);
        fd = open(filename, f, FILE_MODE);
    }
    else if (strcmp(flag, "a") == 0) {
        f = (O_WRONLY | O_CREAT | O_APPEND);
        fd = open(filename, f, FILE_MODE);
    }
    else if (strcmp(flag, "r") == 0) {
        f = O_RDONLY;
        fd = open(filename, f);
    }
    else {
        return NULL;
    }

    if (fd == -1) return NULL;
    
    _FILE *fp = (_FILE*)malloc(sizeof(_FILE));
    if (fp == NULL) {
        close(fd);
        return NULL;
    }
    
    fp->_fileno = fd;
    //fp->_flag = FLUSH_LINE;
    fp->_flag = FLUSH_ALL;
    fp->_out_pos = 0; 

    return fp;
}

int _fwrite(_FILE *fp, const char *s, int len)
{
    // "abcd\n"
    // 没有做异常处理，缓冲区满问题
    // 也不考虑局部问题，假如s是8字节，缓冲区只剩5字节的空间，就应该返回5，这里也不考虑
    memcpy(&fp->_outbuffer[fp->_out_pos], s, len);
    fp->_out_pos += len;

    if (fp->_flag & FLUSH_NOW)
    {
        write(fp->_fileno, fp->_outbuffer, fp->_out_pos);
        fp->_out_pos = 0;
    }
    else if (fp->_flag & FLUSH_LINE)
    {
        if (fp->_outbuffer[fp->_out_pos - 1] == '\n') {
            write(fp->_fileno, fp->_outbuffer, fp->_out_pos);
            fp->_out_pos = 0;
        }
    }
    else if (fp->_flag & FLUSH_ALL)
    {
        if (fp->_out_pos == SIZE)
        {
            write(fp->_fileno, fp->_outbuffer, fp->_out_pos);
            fp->_out_pos = 0;
        }
    }
    return len;    
}

void _fflush(_FILE *fp)
{
    if (fp->_out_pos > 0)
    {
        write(fp->_fileno, fp->_outbuffer, fp->_out_pos);
        fp->_out_pos = 0;
    }
}

void _fclose(_FILE *fp)
{
    if (!fp) return;
    _fflush(fp);
    close(fp->_fileno);
    free(fp);
}


